<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Fetch API 自动补全</title>
  <style>
    #hintBox {
      border: 1px solid #ccc;
      padding: 8px;
      margin-top: 5px;
      width: 200px;
    }
  </style>
</head>
<body>
  <h2>请输入用户名：</h2>
  <input type="text" id="usernameInput" placeholder="输入用户名...">
  <div id="hintBox"></div>

  <script>
    document.getElementById("usernameInput").addEventListener("input", function () {
      const keyword = this.value.trim();
      const hintBox = document.getElementById("hintBox");

      if (keyword === "") {
        hintBox.innerHTML = "";
        return;
      }

      fetch("/user/hint/?q=" + encodeURIComponent(keyword))
        .then(response => {
          if (!response.ok) {
            throw new Error("网络错误：" + response.status);
          }
          return response.json();
        })
        .then(data => {
          if (data.length === 0) {
            hintBox.innerHTML = "<em>无匹配结果</em>";
          } else {
            hintBox.innerHTML = data.map(item => `<div>${item}</div>`).join("");
          }
        })
        .catch(error => {
          console.error("请求出错：", error);
          hintBox.innerHTML = "<span style='color:red'>请求失败</span>";
        });
    });
  </script>
</body>
</html>
